<template>
  <view class="animated fadeIn faster">
    <view class="page-bg">
      <view :style="{'height': titleBarHeight + 'px','paddingTop':statusBarHeight+'px'}"
            class="d-flex d-flex-center d-flex-middle">
        <text :style="{'height': menuButtonHeight-8 + 'px'}" class="font32">课程</text>
      </view>
      <view class="d-flex d-flex-between px-2 d-flex-middle pt-2">
        <view class="searchBox px-2 mx-2 rounded20 d-flex-item d-flex d-flex-middle">
          <input v-model="formData.name" class="pl-1 rounded10 font30 d-flex-item" placeholder="课程名称"
                 placeholder-class="colorhold"/>
          <text v-if="formData.name && formData.name.length > 0" class="mr-2 text-right iconfont icon-cuo1  ml-2"
                @click="dataCancel"></text>
          <text class="iconfont icon-icon_sousuo main-color font40  text" @click="onSearch"></text>
        </view>
      </view>
    </view>

    <view class="d-flex d-flex-between bg-fff mt-2 d-flex-middle px-2">
      <view v-for="(item,index) in courseList" class="pt-2 pb-2" :key=index+1 @click="switchTab(item.id)">
        <text :class="{'grabClassActive':tabsIndex == item.id}" class="font30 main-color">{{ item.name }}</text>
      </view>
      <view class="" style="width:36rpx;height: 36rpx" @click.stop="goUrl('/subPages/selectCourses/selectCourses')">

        <image style="width:36rpx;height: 36rpx"
               src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/exam/courseType.png"></image>
      </view>
    </view>

    <view class="d-flex d-flex-column  px-2 ">
      <view class="sort-container d-flex d-flex-middle py-2">
        <!-- 综合排序 -->
        <view class="sort-item d-flex d-flex-middle" @click="toggleSort('comprehensive')">
          <text class="font28  font-bold" :class="!formData.sort_by&& !formData.sort_order?'main-color':'hui'">综合
          </text>
        </view>

        <!-- 观看人数排序 -->
        <view class="ml-4 sort-item d-flex d-flex-middle" @click="toggleSort('view_count')">
          <text class="font28 hui">观看人数</text>
          <view class="triangle-icons d-flex d-flex-column">
            <text class="iconfont   icon-icon_triangle_  rotate180"
                  :class="formData.sort_by == 'view_count'&& formData.sort_order == 'asc' ?'main-color':'hui'"
                  ></text>
            <text class="  iconfont icon-icon_triangle_  "
                  :class="formData.sort_by == 'view_count'&& formData.sort_order == 'desc' ?'main-color':'hui'"
                  ></text>
          </view>
        </view>

        <view class="ml-4 sort-item d-flex d-flex-middle"  @click="toggleSort('date')">
          <text class="font28 hui">最新日期</text>
          <view class="triangle-icons d-flex d-flex-column">
            <text class="iconfont   icon-icon_triangle_  rotate180"
                  :class="formData.sort_by == 'date'&& formData.sort_order == 'asc' ?'main-color':'hui'"
                 ></text>
            <text class="  iconfont icon-icon_triangle_  "
                  :class="formData.sort_by == 'date' && formData.sort_order == 'desc' ?'main-color':'hui'"
                 ></text>
          </view>
        </view>
      </view>

      <view class="d-flex recommend-grid1">
        <view
            v-for="(item, index) in todayRecommende"
            :key="index"
            class="recommend-data-box d-flex d-flex-column bg-fff rounded10"
            @click="goUrl(`/subPages/courseDetails/courseDetails?id=${item.id}`)"
        >
<!--          VIP 后续可能使用-->
<!--          <view class="vip d-flex d-flex-center ">-->
<!--            <text class="rotate90">VIP</text>-->
<!--          </view>-->
          <image
              class="recommend-picture rounded10"
              :src="item.course_image"
              mode="aspectFill"
          ></image>
          <view class="px-1 pt-1 pb-2">
            <text class="font24" style="color: rgba(55, 189, 180, 1)">免费</text>
            <view class="text-clamp font26 color-5C5C5CFF mt-1">{{ item.course_name }}</view>
            <view class="d-flex d-flex-between d-flex-middle mt-1">
              <text class="font20 color-5C5C5CCC">
                <text>{{ item.sort }}</text>
                位同学正在学习
              </text>
            </view>
          </view>  </view>
      </view>

    </view>

  </view>
</template>

<script>
import {homeApi} from "@/http/homeApi";
import {mapState} from "vuex"

export default {
  data() {
    return {
      courseList: [],
      tabsIndex: 'hot',
      formData: {
        name: '',
        sort_by: '',
        sort_order: ''
      },
      todayRecommende: [],
      currentPage: 1,
      loadingType: 0,
    }
  },
  computed: {
    ...mapState({
      statusBarHeight: state => state.statusBarHeight,
      menuButtonHeight: state => state.menuButtonHeight,
      titleBarHeight: state => state.titleBarHeight,
      avatar: state => state.avatar,
      loginState: state => state.loginState
    }),
  },
  onLoad(options) {
    if (options.id) {
      this.tabsIndex = options.id
    }
    this.goCourseCategories()
    this.goTodayRecommende()
  },
  methods: {
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    async goTodayRecommende() {
      let that = this
      that.loadingType = 1
      try {
        let params = {
          keyword: this.formData.name,
          page: this.currentPage,
          sort_by: this.formData.sort_by,
          sort_order: this.formData.sort_order,
          category_id: this.tabsIndex
        }
        let result = await homeApi.getSearch(params);
        if (result.data) {
          that.todayRecommende = that.todayRecommende.concat(result.data)
        }
        if (result.data && result.data.length > 9) {
          that.loadingType = 0
        } else {
          that.loadingType = 2
        }
      } catch (error) {
        that.loadingType = 2
      }
    },
    async goCourseCategories() {
      let res = await homeApi.getCourseCategories()
      this.courseList = res
    },
    // 搜索功能
    onSearch() {
      if (this.formData.name.trim()) {
        // 执行搜索
        this.currentPage = 1;
        this.todayRecommende = [];
        this.goTodayRecommende();
      } else {
        uni.showToast({
          title: '请输入搜索内容',
          icon: 'none'
        });
      }
    },
    // 清除搜索
    dataCancel() {
      this.formData.name = '';
      // 可以在这里添加清除搜索后的逻辑
    },
    // 排序功能
    toggleSort(type) {
      if (type === 'comprehensive') {
        // 综合排序，清除所有排序
        this.formData.sort_by = '';
        this.formData.sort_order = '';
      } else {
        // 实现三态切换：asc -> desc -> clear -> asc...
        if (this.formData.sort_by === type) {
          if (this.formData.sort_order === 'asc') {
            // 第二次点击：改为降序
            this.formData.sort_order = 'desc';
          } else if (this.formData.sort_order === 'desc') {
            // 第三次点击：清除排序
            this.formData.sort_by = '';
            this.formData.sort_order = '';
          }
        } else {
          // 第一次点击：设置为升序
          this.formData.sort_by = type;
          this.formData.sort_order = 'asc';
        }
      }

      // 重新加载数据
      this.currentPage = 1;
      this.todayRecommende = [];
      this.goTodayRecommende();
    },

    switchTab(id) {
      if (this.tabsIndex !== id) {
        this.tabsIndex = id;
        // 重置分页和数据
        this.currentPage = 1;
        this.todayRecommende = [];
        // 重新加载数据
        this.goTodayRecommende();
      }
    }
  },
  // 加载更多数据
  onReachBottom() {
    console.log('加载更多数据');
    if (this.loadingType == 2 || this.loadingType == 1) {
      return;
    }
    this.currentPage++
    this.goTodayRecommende();
  },
}

</script>

<style scoped>
.page-bg {
  background: linear-gradient(180deg, rgba(62, 142, 254, 0.8) 0%, rgba(62, 142, 254, 0) 100%);
}

.searchBox {
  background-color: #fff;
  height: 80rpx;
  line-height: 80rpx;
}

.searchBox input {
  height: 100%;
}

.grabClassActive {
  font-weight: bold;
  text-decoration: underline;
}

.triangle-icons {
  margin-left: -20rpx;
}

.hui {
  color: rgba(143, 146, 161, 1);
}

.icon-icon_triangle_ {
  font-size: 24rpx; /* 增大字体大小以提高兼容性 */
  transform: scale(0.25); /* 通过缩放保持视觉大小一致 */
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
}

.rotate180 {
  transform:scale(0.25) rotate(180deg);
}

.rotate90 {
  transform: rotate(46deg);
}

.recommend-grid1 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}


.recommend-picture {
  width: 100%;
  height: 348rpx;
  border-radius: 10rpx;
}

.recommend-data-box {
  overflow: hidden;
  position: relative;
  z-index: 1;
}

.vip {
  position: absolute;
  right: 0;
  height: 92rpx;
  width: 96rpx;
  background: linear-gradient(45deg, transparent, transparent 50%, rgba(237, 195, 55, 1) 50%, rgba(214, 137, 60, 1) 100%);
  z-index: 2;
}


</style>
